package com.adv.ems.manager.impl;

import cn.hutool.core.date.DateUtil;
import com.adv.ems.db.mapper.SystemWarningMapper;
import com.adv.ems.db.entity.SystemWarningDO;
import com.adv.ems.manager.SystemWarningManager;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class SystemWarningManagerImpl extends ServiceImpl<SystemWarningMapper, SystemWarningDO> implements SystemWarningManager {
    @Override
    public void insertData(SystemWarningDO warning) {
        save(warning);
    }

    @Override
    public List<SystemWarningDO> getTodayUnReadLastWarning(List<Long> pointIds, Class cls, List<String> types, Integer limit) {
        LambdaQueryWrapper<SystemWarningDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SystemWarningDO::getObjId, pointIds);
        wrapper.in(SystemWarningDO::getObjClsName, cls.getSimpleName());
        wrapper.in(SystemWarningDO::getType, types);
        wrapper.eq(SystemWarningDO :: getState, "UN_READ");
        wrapper.ge(SystemWarningDO :: getUpdateTime, DateUtil.beginOfDay(new Date()));
        wrapper.orderByDesc(SystemWarningDO::getUpdateTime);
        wrapper.last("limit " + limit);
        return list(wrapper);
    }

    @Override
    public List<SystemWarningDO> getList(String type, String state, String fromDate, String toDate, Integer pageNo, Integer pageSize) {
        LambdaQueryWrapper<SystemWarningDO> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasLength(type)) {
            wrapper.eq(SystemWarningDO::getType, type);
        }
        if (StringUtils.hasLength(state)) {
            wrapper.eq(SystemWarningDO::getState, state);
        }
        wrapper.ge(SystemWarningDO :: getUpdateTime, DateUtil.beginOfDay(DateUtil.parseDateTime(fromDate)));
        wrapper.le(SystemWarningDO :: getUpdateTime, DateUtil.endOfDay(DateUtil.parseDateTime(toDate)));
        wrapper.orderByDesc(SystemWarningDO::getUpdateTime);
        wrapper.last("limit " + (pageNo - 1) * pageSize + ", " + (pageSize + 1));
        return list(wrapper);
    }

    @Override
    public void doneAll(List<Long> ids) {
        LambdaQueryWrapper<SystemWarningDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SystemWarningDO::getId, ids);
        SystemWarningDO record = new SystemWarningDO();
        record.setUpdateTime(new Date());
        record.setState("READED");
        update(record, wrapper);
    }
}
